import React, { useEffect, useRef, useState, useCallback } from 'react'
import { connect } from 'react-redux'
import { Text, View, StyleSheet, Image, SafeAreaView, FlatList, TouchableOpacity, Dimensions, TouchableHighlight } from 'react-native'
import { pTx } from "../../utils/dimensions"
import { Badge } from '@pingtou/rn-vant'
import { asyncGetFriendList } from "../../redux/features/appSlice"
import { getDateDiff } from "../../utils/formatDate"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import formatMsg from "../../realm/formatMsg"
import { Popover } from '@pingtou/rn-vant';
import Avatar from "../../components/avatar"
import realmValue from "../../utils/realmValue"
import httpApi from "../../api"

const FlatListChat = (props) => {
    const realm = useRealm();
    const [list, setList] = useState()
    const userInfoList = useQuery(schemaName.UserInfo)
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const friendMsgLis = useQuery(schemaName.FriendMsgLis, friendMsg => {
        return friendMsg.filtered(`UserId == ${userInfo.Id}`)
    })
    const groupMsgLis = useQuery(schemaName.GroupMsgLis, groupMsg => {
        return groupMsg.filtered(`UserId == ${userInfo.Id}`);
    })

    const groupInfoList = useQuery(schemaName.GroupInfo, Info => {
        return Info.filtered(`UserId == ${userInfo.Id}`);
    })

    useEffect(() => {
        getData(userInfo.Id)
        return () => {
        }
    }, [userInfo.Address])
    const getData = useCallback((Id) => {
        const flist = []
        const glist = []
        const friendList = realm.objects(schemaName.FriendList).filtered(`UserId == ${Id}`)
        const groupList = realm.objects(schemaName.GroupList).filtered(`UserId == ${Id}`)
        friendList.forEach((item, index) => {
            let MsgLis = realm.objects(schemaName.FriendMsgLis).filtered(`F == ${item.F} and  UserId == ${Id}  and MT < 40`)
            if (MsgLis.length > 0) {
                let UnreadMsgLis = MsgLis.filtered(`Unread == 1`)
                flist.push({ ...item, ...MsgLis[MsgLis.length - 1], Unread: UnreadMsgLis.length })
            } else {
                flist.push({ ...item, T: 0 })
            }
        })
        groupList.forEach(item => {
            let MsgLis = realm.objects(schemaName.GroupMsgLis).filtered(`G == ${item.G} and  UserId == ${Id}`)
            if (MsgLis.length > 0) {
                let UnreadGroupList = MsgLis.filtered(`Unread == 1`)
                glist.push({ ...MsgLis[MsgLis.length - 1], ...item, Unread: UnreadGroupList.length })
            } else {
                glist.push({ ...item, T: 0 })
            }
        })
        setList(flist.concat(glist).sort((a, b) => b.T - a.T))
    }, [userInfo.Address]);
    const onFriendMsgChange = (msg, changes) => {
        changes.deletions.forEach((index) => {
            getData(userInfo.Id)
        });
        changes.insertions.forEach(async (index) => {
            const newMsg = msg[index]
            const friendList = realm.objects(schemaName.FriendList).filtered(`UserId == ${userInfo.Id} and F == ${newMsg.F} `)
            if (friendList.Id) {
                setList(prev => prev.map((element, idx) => {
                    if (element.F === newMsg.F) {
                        element.Unread = newMsg.S == -1 ? 0 : element.Unread + 1
                        element.MT = newMsg.MT
                        element.M = newMsg.M
                        element.T = newMsg.T
                        return element
                    } else {
                    }
                    return element
                }))
            } else {
                const getFriendList = await httpApi.getFriendList()
                realm.write(() => {
                    getFriendList.data.FriendList && getFriendList.data.FriendList.map(item => realm.create(schemaName.FriendList, { ...item, UserId: userInfo.Id, State: 1 }, true))
                })
                getData(userInfo.Id)
            }
        });
        changes.newModifications.forEach((index) => {
        });
        changes.oldModifications.forEach((index) => {
            const newMsg = msg[index]
            setList(prev => prev.map((element, idx) => {
                if (element.F === newMsg.F) {
                    element.Unread = 0
                    return element
                } else {
                }
                return element
            }))
        });
    }
    const onGroupMsgLisChange = (msg, changes) => {
        changes.deletions.forEach((index) => {
            getData(userInfo.Id)
        });
        changes.insertions.forEach(async (index) => {

            const newMsg = msg[index]
            const groupList = realm.objects(schemaName.GroupList).filtered(`UserId == ${userInfo.Id} and G == ${newMsg.G} `)
            if (groupList.G) {
                getData(userInfo.Id)
            } else {
                if ([65, 98, 99][newMsg.MT] !== -1) {
                    const getGroupList = await httpApi.getGroupList()
                    realm.write(() => {
                        getGroupList.data.GroupList && getGroupList.data.GroupList.map(item => realm.create(schemaName.GroupList, { ...item, UserId: userInfo.Id, State: 1 }, true))
                    })
                }
                setTimeout(() => {
                    getData(userInfo.Id)
                })
            }
        });
        changes.newModifications.forEach((index) => {
            getData(userInfo.Id)
        });
        changes.oldModifications.forEach((index) => {
            getData(userInfo.Id)
        });
    }
    useEffect(() => {
        friendMsgLis.addListener(onFriendMsgChange);
        groupMsgLis.addListener(onGroupMsgLisChange);
        return () => {
            friendMsgLis.removeListener(onFriendMsgChange);
            groupMsgLis.removeListener(onGroupMsgLisChange);

        };
    }, []);

    return (
        <FlatList
            style={{ flex: 1 }}
            renderItem={({ item, index }) => {
                const groupInfo = item.G && groupInfoList.find(el => el.Id == item.G)
                return (
                    <TouchableHighlight underlayColor="rgba(175,181,189,0.2)" key={index} onPress={() => props.navigation.navigate(item.G ? 'groupMsg' : 'friendMsg', { ...JSON.parse(JSON.stringify(item)) })}>
                        <View style={styles.li}>
                            <View style={[styles.row, styles.flexDirectionRow]}>
                                <Badge dot={!!item.Unread}>
                                    <Avatar style={[styles.avatar]} source={{ uri: groupInfo?.Logo || item.L || item.P }}></Avatar>
                                </Badge>
                                <View style={styles.cell}>
                                    <Text style={styles.name}>{groupInfo?.GroupName || item.R}</Text>
                                    <Text style={styles.txt} ellipsizeMode={'tail'} numberOfLines={1}>
                                        {!item.Unread ? '' : `[${item.Unread}条]`}
                                        {["", "", "图片", "视频", "文件", "语音"][item.MT] || item.M}
                                    </Text>
                                </View>
                            </View>
                            {!item.T ? '' : <Text style={styles.time}>{getDateDiff(new Date(item.T * 1000))}</Text>}
                        </View>
                    </TouchableHighlight>
                )
            }}
            data={list}
            keyExtractor={(item, index) => item._id || index}
        />
    )
}

const Chat = (props) => {
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const friendMsgLis = useQuery(schemaName.FriendMsgLis, friend => {
        return friend.filtered(`UserId == ${userInfo.Id} and MT >= 40  and Unread == 1`)
    })
    const { navigation, friendMsg, groupMsg, friendApplyMsg } = props
    const popover = useRef(null);
    const [list, setList] = useState([])
    const iconActions = [
        { text: '添加朋友' },
        { text: '创建群聊', },
        { text: '扫一扫 ', },
    ];

    return (
        <SafeAreaView style={styles.container}>
            <View style={[styles.flexDirectionRow, styles.walletHeaderView]}>
                <Text style={styles.Tweet}>Tweet </Text>
                <View style={styles.flexDirectionRow}>
                    <TouchableOpacity style={styles.FeedbackIcon}>
                        <Image style={[styles.icon, { width: pTx(18), height: pTx(18) }]} source={require('../../assets/image/icon9.png')}></Image>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.FeedbackIcon} onPress={() => navigation.navigate('addressBook')}>
                        <Badge dot={!!friendMsgLis.length}>
                            <Image style={[styles.icon, { width: pTx(24), height: pTx(18) }]} source={require('../../assets/image/icon8.png')}></Image>
                        </Badge>
                    </TouchableOpacity>
                    <Popover ref={popover} theme="dark" duration={0}
                        reference={<TouchableOpacity style={styles.FeedbackIcon}>
                            <Image style={[styles.icon, { width: pTx(18), height: pTx(18) }]} source={require('../../assets/image/icon7.png')}></Image>
                        </TouchableOpacity>}>
                        <View style={styles.PopoverRow}>
                            <TouchableOpacity style={styles.PopoverRowCell} onPress={() => navigation.navigate('addFriends')}>
                                <Image style={styles.PopoverRowCellIcon} source={require('../../assets/image/icon21.png')}></Image>
                                <Text style={styles.PopoverRowCellName}>添加朋友</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.PopoverRowCell} onPress={() => navigation.navigate('createGroupChat')}>
                                <Image style={styles.PopoverRowCellIcon} source={require('../../assets/image/icon19.png')}></Image>
                                <Text style={styles.PopoverRowCellName}>创建群聊</Text>
                            </TouchableOpacity>
                            <View style={styles.PopoverRowCell}>
                                <Image style={styles.PopoverRowCellIcon} source={require('../../assets/image/icon20.png')}></Image>
                                <Text style={styles.PopoverRowCellName}>扫一扫</Text>
                            </View>
                        </View>
                    </Popover>
                </View>
            </View>
            <FlatListChat {...props} />
        </SafeAreaView>
    )
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = { asyncGetFriendList }

export default Chat

const styles = StyleSheet.create({
    walletHeaderView: {
        height: pTx(60),
        paddingHorizontal: pTx(15),
        paddingRight: pTx(8),
        backgroundColor: "rgba(237, 237, 237, 1)"
    },
    flexDirectionRow: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },
    Tweet: {
        fontSize: pTx(18),
        fontWeight: "bold",
        color: "#0A0C14"
    },
    FeedbackIcon: {
        paddingHorizontal: pTx(7),
    },
    container: {
        flex: 1,
        backgroundColor: "#fff",

    },
    PopoverRow: {
        paddingVertical: pTx(9),
    },
    PopoverRowCell: {
        flexDirection: 'row',
        alignItems: "center",
        paddingHorizontal: pTx(20),
        paddingVertical: pTx(9),
    },
    PopoverRowCellName: {
        marginLeft: pTx(12),
        fontSize: pTx(16),
        color: "#FFF",

    },
    PopoverRowCellIcon: {
        width: pTx(18),
        height: pTx(18)
    },
    li: {
        paddingHorizontal: pTx(15),
        flexDirection: 'row',
        justifyContent: "space-between",
        paddingVertical: pTx(15),
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1
    },
    avatar: {
        width: pTx(45),
        height: pTx(45),
        borderRadius: pTx(6),
    },
    cell: {
        marginLeft: pTx(12),
    },
    name: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    txt: {
        marginTop: pTx(5),
        fontSize: pTx(12),
        color: "#AFB5BD",
        maxWidth: Dimensions.get('screen').width - pTx(150),
    },
    time: {
        fontSize: pTx(12),
        color: "#AFB5BD"
    }
})